/*
 * @Description: 菜单权限
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-03-27
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-05-07
 */
import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'

export const useMenu = defineStore('menu', () => {
  const route = useRoute()
  /** 全部菜单：1,2,3级菜单 */
  const menus = ref(<GetPermissionByUserIdTypes.IMenu[]>[])
  /** 菜单：2,3级菜单 */
  const subMenus = computed(() => menus.value[activeNo.value]?.children)
  /** 选中的1级菜单 */
  const activeNo = ref<number>(0)

  watch(
    () => menus.value,
    (val: GetPermissionByUserIdTypes.IMenu[]) => {
      for (let i = 0; i < val.length; i++) {
        const module = val[i]
        const index = module.children?.findIndex((item) => {
          return route.path.indexOf(item.url + '/') === 0 || route.path === item.url
        })
        if (index > -1) {
          activeNo.value = i
          break
        }
      }
    },
    { immediate: true },
  )

  /**
   * 设置菜单
   * @param _menus 菜单
   */
  const setMenus = (_menus: GetPermissionByUserIdTypes.IMenu[]) => (menus.value = _menus)

  /**
   * 设置选中的1级菜单
   * @param _menus 1级菜单序号
   */
  const setActive = (_no: number) => (activeNo.value = _no)

  return { menus, subMenus, activeNo, setMenus, setActive }
})
